package cn.com.fuhuitong.main.order.ui.activity

import android.content.Intent
import android.widget.CheckBox
import androidx.lifecycle.Observer
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.ActivityCollector
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.OrderAction
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.mine.entity.AddressEntity
import cn.com.fuhuitong.main.mine.ui.activity.MineAddressActivity
import cn.com.fuhuitong.main.order.adapter.*
import cn.com.fuhuitong.main.order.entity.SubmitConfirmEntity
import cn.com.fuhuitong.main.order.entity.SubmitGoodsEntity
import cn.com.fuhuitong.main.order.entity.SubmitNatureEntity
import cn.com.fuhuitong.main.order.vm.OrderViewModel
import cn.com.fuhuitong.utils.JsonUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.alibaba.android.vlayout.layout.StickyLayoutHelper
import com.blankj.utilcode.util.LogUtils
import kotlinx.android.synthetic.main.activity_order_submit.*
import org.greenrobot.eventbus.EventBus

@Route(path = ARouteConstance.ACTIVITY_URL_ORDER_SUBMIT)
class OrderSubmitActivity : ViewModeActivity<OrderViewModel>() {

    private var submitConfirmEntity: SubmitConfirmEntity? = null

    private var submitRemark: String = "买家备注信息"

    private var isScore: Int = 0

    private var addressEntity: AddressEntity? = null;

    private lateinit var submitAddressAdapter: OrderSubmitAddressAdapter
    private lateinit var submitGoodsAdapter: OrderSubmitGoodsAdapter
    private lateinit var submitIntegralAdapter: OrderSubmitIntegralAdapter
    private lateinit var submitNatureAdapter: OrderSubmitNatureAdapter
    private lateinit var submitRemarkAdapter: OrderSubmitRemarkAdapter
    private lateinit var submitBottomAdapter: OrderSubmitBottomAdapter

    override fun viewModel(): OrderViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_order_submit

    override fun initView() {

        image_order_submit_back.setOnClickListener {
            this.finish()
        }

        submitConfirmEntity = intent?.getSerializableExtra(AppConstance.BUNDLE_SUBMIT_CONFIRM)
                as SubmitConfirmEntity

        this.initViewRecyclerAdapter(
            recycler_order_submit,
            arrayOf(
                SVT.SUBMIT_ADDRESS.ordinal,
                SVT.SUBMIT_GOODS.ordinal,
                SVT.SUBMIT_INTEGRAL.ordinal,
                SVT.SUBMIT_NATURE.ordinal,
                SVT.SUBMIT_REMARK.ordinal,
                SVT.SUBMIT_BOTTOM.ordinal
            )
        )

        val adapters =
            mutableListOf<DelegateAdapter.Adapter<*>>(
                OrderSubmitAddressAdapter(applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_5)
                }).apply {
                    submitAddressAdapter = this
                },
                OrderSubmitGoodsAdapter(applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_10)
                }).apply {
                    submitGoodsAdapter = this
                },
                OrderSubmitIntegralAdapter(applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_10)
                }).apply {
                    submitIntegralAdapter = this
                },
                OrderSubmitNatureAdapter(applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_10)
                }).apply {
                    submitNatureAdapter = this
                },
                OrderSubmitRemarkAdapter(applicationContext, LinearLayoutHelper().apply {
                    marginTop = resources.getDimensionPixelSize(R.dimen.dp_10)
                    marginBottom = resources.getDimensionPixelSize(R.dimen.dp_10)
                }).apply {
                    submitRemarkAdapter = this
                },
                OrderSubmitBottomAdapter(applicationContext, StickyLayoutHelper(false)).apply {
                    submitBottomAdapter = this
                }
            )
        delegateAdapter.addAdapters(adapters)

        submitAddressAdapter.setOnItemClickListener { view, i, addressEntity ->
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MINE_ADDRESS)
                .withInt(AppConstance.BUNDLE_ADDRESS_TYPE, 1)
                .navigation(this, 100)
        }

        submitIntegralAdapter.setOnItemChildClickListener { view, i, orderListEntity ->
            if (view.id == R.id.fl_order_submit_shop_details){
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                    .withSerializable(
                        AppConstance.BUNDLE_WEB_VIEW,
                        MainBean(type = WebConfig.STORE_CONTECT, data = null)
                    )
                    .navigation()
            }else if (view.id == R.id.cl_order_submit_shop) {
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_HOME_FLAGSHIP_LIST)
                    .navigation(this, 101)
            } else if (view.id == R.id.check_order_submit_switch) {
                val switch = view as CheckBox
                if (switch.isChecked) {
                    viewModel.useScore()
                } else {
                    isScore = 0
                    submitBottomAdapter.setAddDataNew(
                        mutableListOf(submitGoodsEntity.total.toString())
                    )
                    val entityList: MutableList<SubmitNatureEntity> = mutableListOf()
                    submitNatureAdapter.data.forEach {
                        entityList.add(with(it) {
                            this.price = 0.0
                            this
                        })
                    }
                    submitNatureAdapter.setAddDataNew(entityList)
                }
            }
        }
        submitRemarkAdapter.setOnItemChildClickListener { view, i, s ->
            if (view.id == R.id.text_order_submit_remark) {
                submitRemark = s
            }
        }

        submitBottomAdapter.setOnItemChildClickListener { view, i, s ->
            if (view.id == R.id.text_order_submit_comfit) {
                val entity: SubmitConfirmEntity =
                    with(submitConfirmEntity ?: return@setOnItemChildClickListener) {
                        address_id = addressEntity?.id.toString()
                        remarks = if (submitRemark.isEmpty()) "买家备注信息" else submitRemark
                        is_score = isScore.toString()
                        this
                    }
                if (submitGoodsEntity.is_store_display == 1) {
                    if (mFlagshipStoreId == 0) {
                        toast("请选择门店")
                        return@setOnItemChildClickListener
                    }
                    entity.flagship_store_id = mFlagshipStoreId
                }
                viewModel.submitOrder(entity)
            }
        }

    }

    private var mFlagshipStoreId: Int = 0

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                if (data == null) {
                    return
                }
                val address: AddressEntity = data.getSerializableExtra("address")
                        as AddressEntity
                this.addressEntity = address
                submitAddressAdapter.setAddDataNew(mutableListOf(address))
            } else if (requestCode == 101) {
                if (data == null) {
                    return
                }
                mFlagshipStoreId = data.getIntExtra("flagship_store_id", 0)
                val mFlagshipStoreName: String = data.getStringExtra("flagship_store_name")
                    ?: return
                submitIntegralAdapter.setAddDataNew(
                    mutableListOf(
                        SubmitIntegral(
                            flagship_store_id = 1,
                            flagship_store_name = mFlagshipStoreName
                        )
                    )
                )
            }
        }
    }

    private lateinit var submitGoodsEntity: SubmitGoodsEntity
    override fun initViewMode() {

        viewModel.addressDefaultDataLiveData.observe(this, Observer { response ->
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                this.addressEntity = it
                submitAddressAdapter.setAddDataNew(mutableListOf(it))
            }
        })

        viewModel.submitGoodsDataLiveData.observe(this, Observer { response ->
            handlerResponseEmpty(
                status = response.status, message = response.statusTip,
                length = response.response?.data?.goods?.size ?: 0
            )
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                submitGoodsEntity = it
                if (it.goods.isEmpty()) {
                    return@let
                }
                submitAddressAdapter.setAddDataNew(mutableListOf(AddressEntity()))
                submitGoodsAdapter.setAddDataNew(it.goods)
                submitIntegralAdapter.setAddDataNew(mutableListOf(SubmitIntegral(flagship_store_id = it.is_store_display)))
                submitNatureAdapter.setAddDataNew(mutableListOf(SubmitNatureEntity(total = it.total)))
                submitRemarkAdapter.setAddDataNew(mutableListOf(submitRemark))
                submitBottomAdapter.setAddDataNew(
                    mutableListOf(it.total.toString())
                )

                viewModel.addressDefault()
            }
        })

        viewModel.submitNatureDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                isScore = 1
                it.total = submitGoodsEntity.total
                submitNatureAdapter.setAddDataNew(mutableListOf(it))
                submitBottomAdapter.setAddDataNew(
                    mutableListOf((submitGoodsEntity.total - it.price).toString())
                )
            }
        })

        viewModel.submitOrderIdDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                viewModel.orderPay(it.order_id.toInt())
            }
        })

        viewModel.payDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_PAY_WAIT)
                    .withSerializable(AppConstance.BUNDLE_ORDER_PAY, it)
                    .navigation()
            }
        })
    }

    override fun initData() {
        viewModel.confirmOrder(submitConfirmEntity!!)
    }

}